package com.xxkj.drugtraceability.ui.prescriptiondrugback

import android.app.DatePickerDialog
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityPrescriptiondrugbackBinding
import com.xxkj.drugtraceability.databinding.ActivityPrescriptiondrugcollectionBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupCollectTopViewBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupTopViewBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.ui.prescriptiondrugcollection.PrescriptionDrugCollectionAdapter
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*

/**
 * author: zhoujingjin
 * created on: 2024/9/10 14:43
 * description:处方退药采集
 */
class PrescriptionDrugBackActivity:BaseVMActivity() {
    private val binding by binding<ActivityPrescriptiondrugbackBinding>(R.layout.activity_prescriptiondrugback)
    private val viewModel by viewModel<PrescriptionDrugBackViewModel>()
    private lateinit var adapter: PrescriptionDrugBackAdapter
    private lateinit var adapterBottom: PrescriptionDrugBackBottomAdapter
    private var dataObserver: RecyclerView.AdapterDataObserver? = null
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerTop .layoutManager = LinearLayoutManager(this@PrescriptionDrugBackActivity,LinearLayoutManager.HORIZONTAL,false)
            recyclerView.layoutManager = LinearLayoutManager(this@PrescriptionDrugBackActivity)
            adapter = PrescriptionDrugBackAdapter{
                viewModel.topIndex = it
                viewModel.topList.value?.forEachIndexed { index, patientDrugData ->
                    patientDrugData.isSelected = index==it
                }
                adapter.notifyDataSetChanged()
                viewModel.topList.value?.let { list->
                    viewModel.nowRxno = list[it].rxno?:""
                    viewModel.queryPrescriptionInfoList()
                }
            }
            adapterBottom = PrescriptionDrugBackBottomAdapter{
                viewModel.barcode = ""
            }
            recyclerTop.adapter = adapter
            recyclerView.adapter = adapterBottom

            dataObserver = object : RecyclerView.AdapterDataObserver() {
                override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
                    if (adapterBottom.data.isEmpty()) {
                        runOnUiThread {
                            viewModel.topData.clear()
                        }
                    }
                }
            }
            adapterBottom.registerAdapterDataObserver(dataObserver!!)
            tvCancel.clickN {
                YellowDialog(this@PrescriptionDrugBackActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvSave.clickN {
                var noData = true
                adapterBottom.data.forEach {
                    if (!it.drugTracInfoList.isNullOrEmpty()){
                        noData = false
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(
                        this@PrescriptionDrugBackActivity,
                        resources.getString(R.string.no_data),
                        type = 1
                    ) {

                    }
                } else {
                    //保存数据
                    viewModel.finishScanBackDrugCode(
                        FinishRequest(
                            "1",
                            viewModel.prescriptioninfo.value,
                            viewModel.Prescriptionbarcode
                        )
                    )
                }
            }

        }
    }

    override fun initData() {

    }

    override fun startObserve() {
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
            }
        })
        viewModel.topList.observe(this, Observer {
           it.forEachIndexed { index, patientDrugData ->
               patientDrugData.isSelected = index==viewModel.topIndex
           }
            adapter.setList(it)
            if (it.isEmpty()&&adapterBottom.data.size>0){
                viewModel.prescriptioninfo.postValue(mutableListOf())
            }
        })
        viewModel.prescriptioninfo.observe(this, Observer { list->
            if (!list.isNullOrEmpty()&& list.isNotEmpty()){
                val prescr = list[0]
                prescr.let {
                    it.dataForm = "02"
                    binding.llBottom.visibility = View.VISIBLE
                    if (it.drugInfoList.isNullOrEmpty()) {
                        adapterBottom.setList(mutableListOf())
                        adapterBottom.setEmptyView(R.layout.layout_nodata)
                    } else {
                        adapterBottom.setList(it.drugInfoList)
                    }
                }
            } else {
                binding.llBottom.visibility = View.GONE
                adapterBottom.setList(mutableListOf())
                adapterBottom.setEmptyView(R.layout.layout_nodata)

            }

        })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@PrescriptionDrugBackActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if (viewModel.topData.isEmpty()){
                            //按处方码扫
                            //无值扫的算处方码
                            viewModel.nowRxno = barcodeMessage.barcode
                            viewModel.queryPrescriptionInfoList()
                        }else{
                            YellowDialog(this@PrescriptionDrugBackActivity,"请先处理当前展示处方退药",type = 1){}

                        }
                    }
                }
            }
        }
    }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        dataObserver?.let { adapterBottom.unregisterAdapterDataObserver(it) }
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}